package tech.mhuang.pacebox.springboot.core.controller;

import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import tech.mhuang.pacebox.core.date.DateTimeUtil;
import tech.mhuang.pacebox.core.util.StringUtil;

import java.beans.PropertyEditorSupport;
import java.time.LocalDate;
import java.util.Date;

/**
 * 通用控制层
 *
 * @author mhuang
 * @since 1.0.0
 */
public abstract class BaseController {


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String text) {
                if (StringUtil.isEmpty(text)) {
                    return;
                }
                try {
                    setValue(DateTimeUtil.parseDateTimeToDate(text));
                } catch (Exception e) {
                    setValue(DateTimeUtil.localDateToStartDate(LocalDate.parse(text)));
                }
            }
        });
    }

    /**
     * 页面跳转
     *
     * @param url 跳转的url
     * @return string
     */
    public String redirect(String url) {
        //节省开支
        return new StringBuilder(url.length() + 10).append("redirect").append(url).toString();
    }
}
